package com.executor.gateway.service.impl;

import com.alibaba.fastjson.JSON;
import com.executor.gateway.mapper.MetricsMapper;
import com.executor.gateway.model.po.Metrics;
import com.executor.gateway.service.MetricsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version v1.0
 * @ClassName: MetricsServiceImpl
 * @Description: 统计的service
 * @author: miaoguoxin
 * @date: 2019/6/29 17:30
 */
@Service
@Slf4j
public class MetricsServiceImpl implements MetricsService {
    @Autowired
    private MetricsMapper metricsMapper;

    private static Map<String, Metrics> metricsMap = new ConcurrentHashMap<>();

    @Override
    public void incOneCount2MetricsMap(String uri, String countParam) {
        Metrics metrics = metricsMap.getOrDefault(uri, new Metrics());
        metrics.setReqUri(uri);
        Class<?> aClass = metrics.getClass();
        try {
            Field field = aClass.getDeclaredField(countParam);
            field.setAccessible(true);
            int count = Integer.parseInt(field.get(metrics).toString());
            field.set(metrics,count+1);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("没有对应的字段",e);
        }
        metricsMap.putIfAbsent(uri,metrics);
       // log.info(JSON.toJSONString(metricsMap));
    }


    @Override
    public void save2Db() {
        List<Metrics> metrics=new ArrayList<>(metricsMap.values());
        if (metrics.isEmpty()){
            return;
        }
        metricsMapper.insertBatchMetrics(metrics);
        metricsMap.clear();
    }
}
